package de.lgohlke.compress;

import org.apache.commons.codec.binary.Base64;

import de.lgohlke.collection.SavedSpace;

/**
 * <p>StringCompressorV1 class.</p>
 *
 * @author lars
 * @version $Id: $
 */
public class StringCompressorV1 implements ICompressor<String>
{
  private final static Base64              base       = new Base64(false);
  private final static ICompressor<byte[]> compressor = new ByteCompressor();

  /*
   * (non-Javadoc)
   * @see de.lgohlke.AST.ICompressor#compress(java.lang.Object)
   */
  /**
   * <p>compress.</p>
   *
   * @param value a {@link java.lang.String} object.
   * @return a {@link de.lgohlke.compress.CompressableValue} object.
   */
  public CompressableValue<String> compress(final String value)
  {
    CompressableValue<String> result = null;
    if ((value != null))
    {
      CompressableValue<byte[]> voByte = compressor.compress(value.getBytes());

      if (voByte.isCompressed())
      {
        result = new CompressableValue<String>(base.encodeAsString(voByte.getRaw()), true);
      }
      else
      {
        result = new CompressableValue<String>(value, false);
      }
    }
    else
    {
      result = new CompressableValue<String>(null, false);
    }
    return result;
  }

  /*
   * (non-Javadoc)
   * @see de.lgohlke.AST.ICompressor#decompress(java.lang.Object)
   */
  /** {@inheritDoc} */
  public String decompress(final CompressableValue<String> vo)
  {
    if (vo.isCompressed())
    {
      CompressableValue<byte[]> voByte = new CompressableValue<byte[]>(null, true, base.decode(vo.getValue()));
      byte[] uncompressed = compressor.decompress(voByte);
      return new String(uncompressed);
    }
    else
    {
      return vo.getValue();
    }
  }

  /*
   * (non-Javadoc)
   * @see de.lgohlke.AST.ICompressor#savedSpace(java.lang.Object)
   */
  /** {@inheritDoc} */
  public SavedSpace savedSpace(final CompressableValue<String> vo)
  {
    SavedSpace savedSpace = new SavedSpace();

    if (vo.isCompressed() && (vo.getValue() != null))
    {
      int compressed = vo.getValue().length();
      int raw = decompress(vo).getBytes().length;
      savedSpace.setRawSize(raw);
      savedSpace.setSavedSize(raw - compressed);
    }

    return savedSpace;
  }
}
